package com.shouxin.attendance.utils;

import android.app.KeyguardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.annotation.DrawableRes;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;

import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.shouxin.attendance.App;
import com.shouxin.attendance.R;

import org.apache.log4j.Logger;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.security.MessageDigest;
import java.util.regex.Pattern;

public final class Utils {

    private static final byte CPU_TYPE_DEFAULT = 0x0;

    private static final byte CPU_TYPE_ARM_V5 = 0x1;

    private static final byte CPU_TYPE_ARM_V6 = 0x2;

    private static final byte CPU_TYPE_ARM_V7 = 0x3;

    private static final Logger logger = Logger.getLogger(Utils.class);

    /**
     * 获取版本
     */
    public static int getAppVersion() {
        try {
            PackageManager pm = App.getApp().getPackageManager();
            PackageInfo pi = pm.getPackageInfo(App.getApp().getPackageName(), 0);
            return pi.versionCode;
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 获取版本
     */
    public static String getAppVersionName() {
        try {
            PackageManager pm = App.getApp().getPackageManager();
            PackageInfo pi = pm.getPackageInfo(App.getApp().getPackageName(), 0);
            return pi.versionName;
        } catch (Exception e) {
            return "1.0.0";
        }
    }

    public static short getTerminalVersion() {
        String version = Build.VERSION.RELEASE;
        return (short) (Integer.parseInt(version.replace(".", "").substring(0, 2)));
    }

    /**
     * 获取CPU类型
     *
     * @return byte CPU类型：{@link #CPU_TYPE_DEFAULT}, {@link #CPU_TYPE_ARM_V5}, {@link #CPU_TYPE_ARM_V6}, {@link
     * #CPU_TYPE_ARM_V7},
     */
    public static byte getCpuType() {
        String cpuName = getCpuName();
        if (cpuName == null || cpuName.length() == 0) {
            return CPU_TYPE_DEFAULT;
        }

        if (cpuName.contains("ARMv7")) {
            return CPU_TYPE_ARM_V7;
        } else if (cpuName.contains("ARMv6")) {
            return CPU_TYPE_ARM_V6;
        } else if (cpuName.contains("ARMv5")) {
            return CPU_TYPE_ARM_V5;
        }

        return CPU_TYPE_DEFAULT;
    }

    private static String getCpuName() {
        FileReader fr = null;
        BufferedReader br = null;
        String[] array = null;
        try {
            fr = new FileReader("/proc/cpuinfo");
            br = new BufferedReader(fr);
            String text = br.readLine();
            array = text.split(":\\s+", 2);
        } catch (IOException e) {
            logger.error("Get cpu name failed! message =>" + e.getMessage());
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
                if (fr != null) {
                    fr.close();
                }
            } catch (IOException e) {
                logger.error("close failed! message =>" + e.getMessage());
            }
        }
        if (array != null && array.length >= 2) {
            return array[1];
        }
        return null;
    }

    /**
     * 获取手机厂商名称
     */
    public static String getManufacturer() {
        return Build.MANUFACTURER;
    }

    /**
     * 获取手机型号
     */
    public static String getPhoneModel() {
        return Build.MODEL;
    }

    /**
     * 获取手机IMEI
     */
    public static String getIMEI(Context context) {
        String androidId = Settings.System.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);

        final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        String imei = tm.getDeviceId();
        if (TextUtils.isEmpty(imei)) {
            imei = androidId;
            if (TextUtils.isEmpty(imei)) {
                imei = "0000000000000000";
            }
        }
        if (imei.length() < 16) {
            imei = imei + "0";
        } else if (imei.length() > 16) {
            imei = imei.substring(0, 15);
        }
        return imei;
    }

    public static void wakeUpAndUnlock(Context context) {
        KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
        KeyguardManager.KeyguardLock kl = km.newKeyguardLock("unLock");
        //解锁
        kl.disableKeyguard();
        //获取电源管理器对象
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        //获取PowerManager.WakeLock对象,后面的参数|表示同时传入两个值,最后的是LogCat里用的Tag
        PowerManager.WakeLock wl = pm
                .newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK, "bright");
        //点亮屏幕
        wl.acquire();
        //释放
        wl.release();
    }

    public static String getDisplayStr() {
        DisplayMetrics displayMetrics = App.getApp().getResources().getDisplayMetrics();
        return displayMetrics.widthPixels + "x" + displayMetrics.heightPixels;
    }

    public static String getSDCardPath() {
        if (isSDCardExist()) {
            return Environment.getExternalStorageDirectory().getAbsolutePath();
        } else {
            return Environment.getDataDirectory().getAbsolutePath();
        }
    }

    public static boolean isSDCardExist() {
        String state = Environment.getExternalStorageState();
        return state.equals(Environment.MEDIA_MOUNTED);
    }

    public static boolean isNetConnected() {
        ConnectivityManager connectivityManager = (ConnectivityManager) App.getApp().getSystemService(
                Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetInfo != null && activeNetInfo.isConnected();
    }

    public static boolean isPhoneValid(String phoneNumber) {
        String expression = "((^1[0-9]{10}$)|(^0[1,2]{1}\\d{1}-?\\d{8}$)|(^0[3-9] {1}\\d{2}-?\\d{7,8}$)|(^0[1,2]{1}\\d{1}-?\\d{8}-(\\d{1,4})$)|(^0[3-9]{1}\\d{2}-? \\d{7,8}-(\\d{1,4})$))";
        return phoneNumber.matches(expression);
    }

    public static boolean isPlateNoValid(String plateNumber) {
        String expression = "^[\\u4e00-\\u9fa5]{1}[A-Z]{1}[A-Z_0-9]{5}$";
        return plateNumber.matches(expression);
    }

    public static boolean isEmail(String email) {
        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        return email.matches(str);
    }

    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    public static String md5(String s) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            byte[] strTemp = s.getBytes();
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(strTemp);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (byte b : md) {
                str[k++] = hexDigits[b >>> 4 & 0xf];
                str[k++] = hexDigits[b & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }

    public static void deleteAPK(Context context) {
        Uri uri = Uri.parse("package:com.sailing.attendance");
        Intent intent = new Intent(Intent.ACTION_DELETE);
        intent.setData(uri);
        context.startActivity(intent);
    }

    public static DisplayImageOptions buildDisplayOptions(@DrawableRes int drawable) {
        // 初始化ImageLoader
        DisplayImageOptions.Builder optionsBuilder = new DisplayImageOptions.Builder();
        // 设置图片Uri为空或是错误的时候显示的图片
        optionsBuilder.showImageForEmptyUri(drawable);
        // 设置图片加载/解码过程中错误时候显示的图片
        optionsBuilder.showImageOnFail(drawable);
        optionsBuilder.showImageOnLoading(drawable);
        optionsBuilder.resetViewBeforeLoading(true);
        // 设置下载的图片是否缓存在内存中
        optionsBuilder.cacheInMemory(true);
        // 设置下载的图片是否缓存在SD卡中
        optionsBuilder.cacheOnDisk(true);
        // 是否考虑JPEG图像EXIF参数（旋转，翻转）
        optionsBuilder.considerExifParams(false);
        // 设置图片的解码类型,默认值——Bitmap.Config.ARGB_8888
        optionsBuilder.bitmapConfig(Bitmap.Config.RGB_565);
        optionsBuilder.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2);

        return optionsBuilder.build();
    }

    public static void initGlobalImageLoader()
    {
        ImageLoaderConfiguration.Builder configBuilder = new ImageLoaderConfiguration.Builder(App.getApp());
        configBuilder.diskCache(new UnlimitedDiskCache(new File(FileUtils.PHOTO_DIR), null, new Md5FileNameGenerator()));
        configBuilder.threadPoolSize(10);
        configBuilder.tasksProcessingOrder(QueueProcessingType.FIFO);
        //configBuilder.writeDebugLogs();
        configBuilder.defaultDisplayImageOptions(Utils.buildDisplayOptions(R.mipmap.default_photo));

        ImageLoaderConfiguration config = configBuilder.build();
        ImageLoader.getInstance().init(config);
    }
}
